//
//  OMDeliveryAddressModifyViewController.m
//  OMENGO
//
//  Created by 梁尚嘉 on 2016/12/23.
//  Copyright © 2016年 Kamfat. All rights reserved.
//

#import "OMDeliveryAddressModifyViewController.h"
#import "OMDeliveryAddressSelectionViewController.h"
#import "KTEleInputTableCell.h"
#import "OMDeliveryInfo.h"
#import "OMOriginalAddress.h"
NSString *const OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION = @"OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION";
#import "OMSelectionCtrlProtocol.h"
@interface OMDeliveryAddressModifyViewController () <OMSelectionCtrlProtocol>
@property (nonatomic, strong) KTEleInputTableCell *addressCell;
@property (nonatomic, strong) KTEleInputTableCell *moreAddressCell;
@property (nonatomic, strong) KTEleInputTableCell *nameCell;
@property (nonatomic, strong) KTEleInputTableCell *phoneCell;

@property (nonatomic, strong) OMOriginalAddress *item;
@end

@implementation OMDeliveryAddressModifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.title = self.isModifying ? @"修改地址":@"新增地址";

    [self.tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(@(64));
    }];

    UIView *footer = [UIView new];
    footer.backgroundColor = SM_whiteColor;
    [self.view addSubview:footer];
    [footer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.height.equalTo(@(SM_SIZE(130)));
        make.left.right.bottom.equalTo(@0);
    }];
    UIButton *confirmBtn = [UIButton new];
    [confirmBtn setBackgroundImage:[UIImage imageWithColor:SM_sangouColor] forState:UIControlStateNormal];
    [confirmBtn setBackgroundImage:[UIImage imageWithColor:SM_disableColor] forState:UIControlStateDisabled];
    [confirmBtn setTitle:self.isModifying?@"确认修改":@"新增地址" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:SM_blackColor forState:UIControlStateNormal];
    [confirmBtn setTitleColor:SM_whiteColor forState:UIControlStateDisabled];
    [confirmBtn.layer setCornerRadius:SM_SIZE(10)];
    [confirmBtn setClipsToBounds:YES];
    [confirmBtn.titleLabel setFont:SM_CFont(34)];
    [confirmBtn addTarget:self action:@selector(confirmBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [footer addSubview:confirmBtn];
    [confirmBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(SM_SIZE(20)));
        make.right.bottom.equalTo(@(SM_SIZE(-20)));
    }];
    UIView *line = [UIView new];
    line.backgroundColor = SM_naviShadowColor;
    [footer addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(@0);
        make.height.equalTo(@(.5f));
    }];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    self.tableView.separatorColor = SM_placeholdColor;
    self.tableView.rowHeight = [KTEleInputTableCell cellHeight];

    self.addressCell = [KTEleInputTableCell new];
    self.addressCell.inputTF.placeholder = @"请选择楼盘";
    self.addressCell.inputTF.enabled = NO;
    self.addressCell.elementLabel.text = @"地址";
    self.addressCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    self.moreAddressCell = [KTEleInputTableCell new];
    self.moreAddressCell.elementLabel.text = @"详细地址";
    self.moreAddressCell.inputTF.placeholder = @"请输入楼盘下的地址";

    self.nameCell = [KTEleInputTableCell new];
    self.nameCell.elementLabel.text = @"收货人";
    self.nameCell.inputTF.placeholder = @"请输入联系人的姓名";

    self.phoneCell = [KTEleInputTableCell new];
    self.phoneCell.elementLabel.text = @"手机号";
    self.phoneCell.inputTF.placeholder = @"请输入手机号码";
    self.phoneCell.inputTF.keyboardType = UIKeyboardTypeNumberPad;


    if (self.isModifying) {
        self.addressCell.inputTF.text = self.info.areaName;
        self.nameCell.inputTF.text = self.info.consignee;
        self.phoneCell.inputTF.text = self.info.phone;
        self.moreAddressCell.inputTF.text = self.info.address;
    }

    @weakify(self);
    [[RACSignal combineLatest:@[self.phoneCell.inputTF.rac_textSignal,self.moreAddressCell.inputTF.rac_textSignal,self.nameCell.inputTF.rac_textSignal,RACObserve(self, item)]
                      reduce:^id{
                          @strongify(self);
                          if (!self.info&&!self.item) {
                              return @(NO);
                          }else if (!self.moreAddressCell.inputTF.text.length) {
                              return @(NO);
                          }else if (!self.phoneCell.inputTF.text.length) {
                              return @(NO);
                          }else if (!self.nameCell.inputTF.text.length) {
                              return @(NO);
                          }else if (![self.phoneCell.inputTF.text isMobile]) {
                              if (self.phoneCell.inputTF.text.length == 11) {
                                  [OMHUD HUDInfo:@"请输入正确的手机号"];
                              }
                              self.phoneCell.layer.borderColor = SM_thumeColor.CGColor;
                              self.phoneCell.layer.borderWidth = .7f;
                              return @(NO);
                          }else {
                              self.phoneCell.layer.borderColor = nil;
                              self.phoneCell.layer.borderWidth = 0;
                          }
                          return @(YES);
    }] subscribeNext:^(id x) {
        confirmBtn.enabled = [x boolValue];
    }];

}

- (void)confirmBtnClick:(UIButton *)btn
{

    [self.view endEditing:YES];
    [OMHUD HUDLoading:nil];
    if (self.isModifying) {
        [self modifyAddress];
    }else {
        [self addAddress];
    }
}

- (void)modifyAddress
{

    [KTHttpUtils POST:@"receiver/update.jhtml"
           parameters:@{
                        @"receiver.area_id":self.item.id.length?self.item.id:(self.info.areaId?self.info.areaId:@""),
                        @"receiver.address":self.moreAddressCell.inputTF.text,
                        @"receiver.consignee":self.nameCell.inputTF.text,
                        @"receiver.phone":self.phoneCell.inputTF.text,
                        @"receiver.id":self.info.id,
                        }
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {
               if (isSuccess) {
                   [OMHUD HUDHide];
                   SMNotificationPost(OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION, nil);
                   NaviPopAnimated(YES);
               }else {
                   [OMHUD HUDError:message];
               }
           }];
}

- (void)addAddress
{
    [KTHttpUtils POST:@"receiver/save.jhtml"
           parameters:@{
                        @"receiver.area_id":self.item.id,
                        @"receiver.address":self.moreAddressCell.inputTF.text,
                        @"receiver.consignee":self.nameCell.inputTF.text,
                        @"receiver.phone":self.phoneCell.inputTF.text,
                        }
             progress:nil
           completion:^(id responseObject, BOOL isSuccess, NSString *message) {
               if (isSuccess) {
                   [OMHUD HUDHide];
                   SMNotificationPost(OMDELIVERTY_ADDRESS_SAVE_SUCCESS_NOTIFICATION, nil);
                   NaviPopAnimated(YES);
               }else {
                   [OMHUD HUDError:message];
               }
           }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - tableview delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 2:return self.addressCell;
        case 3:return self.moreAddressCell;
        case 0:return self.nameCell;
        case 1:return self.phoneCell;
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.row) {
        case 2:{
            NaviPush(@"OMHomeAddressSelectViewController", (@{@"title":@"选择地址",@"delegate":self}));
        };
        case 0:return;
        case 1:return;
        case 3:return;
    }
}

#pragma mark - OMSelectionCtrlProtocol
- (void)ctrl:(id)controller didSelectObject:(OMOriginalAddress *)address
{
    self.item = address;
    self.addressCell.inputTF.text = address.name;
}



@end
